#include "laserbullet.h"
#include "player.h"
namespace fireplane
{
	LaserBullet::LaserBullet():
		_is_finish(false)
	{	
	}

	LaserBullet::~LaserBullet(){
	}

	void LaserBullet::init(Bullet::BulletCommand* cmd){
		_speed = cmd->_speed;
		_dir = cmd->_dir;
		_owner = cmd->o;

		char buffer[0xff];
		sprintf(buffer,"%s","bullet/npc2/0.png");
		_body = CCSprite::create(buffer);
		_body->setAnchorPoint(CCPointMake(0.5f,0.0f));

		float degree = CC_RADIANS_TO_DEGREES(acos(ccpDot(_dir,ccp(0,1))));
		if (ccpCross(_dir,ccp(0,1)) < 0)
		{
			degree = 360 - degree;
		}

		_body->setRotation(degree);
		_all_bullets_parent->addChild(this);
		this->addChild(_body);
		this->setPosition(cmd->_pos);

		_startPos = cmd->_pos;
		_startAngle = 0;

		CCScaleTo* s0 = CCScaleTo::create(0.2f,1.0f,1.5f);
		CCCallFunc* call = CCCallFunc::create(this,callfunc_selector(LaserBullet::scale2Long));
		CCDelayTime* delay = CCDelayTime::create(2.0f);
		CCCallFunc* call1 = CCCallFunc::create(this,callfunc_selector(LaserBullet::finish));
		CCSequence* seq = CCSequence::create(s0,call,delay,call1,NULL);
		_body->runAction(seq);
		_body->runAction(CCFadeOut::create(2.0f));
	}

	void LaserBullet::finish(){
		_is_finish = true;
	}

	void LaserBullet::scale2Long(){
		CCPoint pos_player = Player::getMainPlayer()->getPlayerPos();
		CCPoint dir = ccpSub(_startPos,pos_player);
		float dis = ccpLength(dir);
		CCSize conSize = _body->getContentSize();
		float scaleY =dis/conSize.height ;

		_body->setScaleY(scaleY);
	}

	bool LaserBullet::updateState(float dt){
		if (isDestroy())
		{
			return false;
		}

		CCSize winSize = CCDirector::sharedDirector()->getWinSize();
		CCRect rect = CCRectMake(0,0,winSize.width,winSize.height);

		CCPoint pos = this->getPosition();
		CCPoint worldpos = this->getParent()->convertToWorldSpace(pos);

		if (rect.containsPoint(worldpos))
		{
			return !_is_finish;
		}
		else
		{
			// out of screen
			return false;
		}

	}
}